package tk.leafotto.sign2.activity;

import android.animation.ObjectAnimator;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;

import tk.leafotto.sign2.R;
import tk.leafotto.sign2.dao.DbUtils;
import tk.leafotto.sign2.utils.TimeUtil;

public class MainActivity extends Activity {


    private ArrayList<String> mAllPlayerList;
    private MyAdapter mAdapter;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 0:
                    if(mAdapter == null){
                        mAdapter = new MyAdapter();
                        lv.setAdapter(mAdapter);
                    }else {
                        mAdapter.notifyDataSetChanged();
                    }
                    if(oa != null){
                        oa = ObjectAnimator.ofFloat(ll_main, "translationX", 0);
                        oa.setDuration(1);
                        oa.start();
                    }
                    break;
                case 2:
                    Toast.makeText(getApplicationContext(),"姓名修改失败，请检查是否存在重名",Toast.LENGTH_SHORT).show();
                    break;
            }

        }
    };
    private HashMap<String, String> mSignDate;
    private HashMap<String,String> mPlayerCount;
    private DbUtils dbUtils;
    private ListView lv;
    private ObjectAnimator oa;
    private int startX;
    private LinearLayout ll_main;
    private EditText editText;
    private String newName;
    private long mExitTime;
    private int btDelWidth;
    private ViewHolder holder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);

    }

    @Override
    protected void onResume() {
        super.onResume();
        initUI();
        initData();
    }

    private void initData() {
        new Thread(){

            @Override
            public void run() {
                dbUtils = DbUtils.instance(getApplicationContext());
                mAllPlayerList = dbUtils.getAllPlayer();
                if (mAllPlayerList != null && mAllPlayerList.size() > 0) {
                    mSignDate = new HashMap<String, String>();
                    mPlayerCount = new HashMap<String, String>();
                    for (String name : mAllPlayerList) {
                        String lastSign = dbUtils.getLastSign(name);
                        mSignDate.put(name,lastSign);
                        String signCount = dbUtils.getSignCount(name) + "";
                        mPlayerCount.put(name,signCount);
                    }
                }
                System.out.println("---------------------------------"+mAllPlayerList);
                mHandler.sendEmptyMessage(0);
            }
        }.start();
    }

    private void initUI() {
        Button bt_toadd = (Button) findViewById(R.id.bt_toadd);
        bt_toadd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getApplicationContext(), SetupActivity.class);
                startActivity(intent);
            }
        });
        lv = (ListView) findViewById(R.id.lv);
        Button bt_add = (Button) findViewById(R.id.bt_add);
        bt_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(), SetupActivity.class);
                startActivity(intent);
            }
        });
        SearchView sv = (SearchView) findViewById(R.id.sv);
    }

    class MyAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return mAllPlayerList.size();
        }

        @Override
        public Object getItem(int position) {
            return mAllPlayerList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, final ViewGroup parent) {
            holder = null;
            if(convertView == null){
                convertView = convertView.inflate(getApplicationContext(),R.layout.item_listview_main,null);
                holder = new ViewHolder();
                holder.tv_name = (TextView) convertView.findViewById(R.id.tv_name);
                holder.count = (TextView) convertView.findViewById(R.id.count);
                holder.tv_date = (TextView) convertView.findViewById(R.id.tv_date);
                holder.bt_sign = (Button) convertView.findViewById(R.id.bt_sign);
                holder.bt_signed = (Button) convertView.findViewById(R.id.bt_signed);
                holder.bt_delplayer = (Button)convertView.findViewById(R.id.bt_delplayer);

                convertView.setTag(holder);
            }else {
                holder = (ViewHolder) convertView.getTag();
            }

            holder.tv_name.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getApplicationContext(), SignActivity.class);
                    intent.putExtra("name",mAllPlayerList.get(position));
                    startActivity(intent);
                }
            });

            //长按姓名修改
            holder.tv_name.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setTitle("姓名修改");
                    editText = new EditText(getApplicationContext());
                    editText.setHint("请输入正确的姓名");
                    editText.setTextColor(Color.BLACK);
                    editText.setBackgroundColor(Color.WHITE);
                    editText.setGravity(View.TEXT_ALIGNMENT_CENTER);
                    LinearLayout linearLayout = new LinearLayout(getApplicationContext());
                    linearLayout.setPadding(30,10,10,30);
                    linearLayout.addView(editText);

                    builder.setView(linearLayout);
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            newName = editText.getText().toString().trim();
                            if(newName.isEmpty()){
                                Toast.makeText(getApplicationContext(),"姓名不能为空",Toast.LENGTH_SHORT).show();
                            }else {
                                dialog.dismiss();
                                new Thread(){
                                    @Override
                                    public void run() {
                                        int result = DbUtils.instance(getApplicationContext()).changeName(mAllPlayerList.get(position), newName);
                                        if(result > 0){
                                            //原姓名的数据对应到新姓名
                                            String signData = mSignDate.get(mAllPlayerList.get(position));
                                            String playerCount = mPlayerCount.get(mAllPlayerList.get(position));
                                            mSignDate.put(newName,signData);
                                            mPlayerCount.put(newName,playerCount);
                                            mAllPlayerList.set(position,newName);
                                            mHandler.sendEmptyMessage(0);
                                        }else {
                                            mHandler.sendEmptyMessage(2);
                                        }
                                    }
                                }.start();
                            }
                        }
                    });
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            System.out.println("取消被点击" + which);
                            dialog.dismiss();
                        }
                    });
                    builder.show();
                    return true;
                }
            });

            //删除按钮
            holder.bt_delplayer.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); //必须用this，不能用getApplicationContext
                    builder.setTitle("警告");
                    builder.setMessage("学员" + mAllPlayerList.get(position) + "及其所关联的数据将被删除");
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            new Thread(){
                                @Override
                                public void run() {
                                    int result = dbUtils.delName(mAllPlayerList.get(position));
                                    if(result > 0){
                                        mAllPlayerList.remove(mAllPlayerList.get(position));
                                        mHandler.sendEmptyMessage(0);
                                    }
                                }
                            }.start();
                            dialog.dismiss();
                        }
                    });
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.show();
                }
            });


            //todo 删除动画
            convertView.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    int action = event.getAction();
                    btDelWidth = holder.bt_sign.getWidth();

                    switch (action){
                        case MotionEvent.ACTION_DOWN:
                            startX = (int)event.getX();
                            break;

                        case MotionEvent.ACTION_MOVE:
                            int stopX = (int) event.getX();
                            if(startX - stopX > 160){
                                if (oa != null){
                                    oa = ObjectAnimator.ofFloat(ll_main, "translationX", 0);
                                    oa.setDuration(400);
                                    oa.start();
                                }
                                ll_main = (LinearLayout) v.findViewById(R.id.ll_main);
                                oa = ObjectAnimator.ofFloat(ll_main, "translationX", -btDelWidth);
                                oa.setDuration(400);
                                oa.start();
                            }else if(stopX - startX > 150){
                                ll_main = (LinearLayout) v.findViewById(R.id.ll_main);
                                oa = ObjectAnimator.ofFloat(ll_main, "translationX", 0);
                                oa.setDuration(400);
                                oa.start();
                            }
                            break;
                        case MotionEvent.ACTION_UP:
                            break;
                    }
                    return true;
                }
            });


            //签到按钮
            holder.bt_sign.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    new Thread(){
                        @Override
                        public void run() {
                            dbUtils = DbUtils.instance(getApplicationContext());
                            //签到信息写入数据库
                            long result = dbUtils.sign(mAllPlayerList.get(position), TimeUtil.getDate());
                            if(result > 0){
                                String name = mAllPlayerList.get(position);
                                mSignDate.put(name, TimeUtil.getDate());
                                String count = Integer.parseInt(mPlayerCount.get(name)) + 1 + "";
                                mPlayerCount.put(name, count);
                                mHandler.sendEmptyMessage(0);
                            }
                        }
                    }.start();
                }
            });

            String name = mAllPlayerList.get(position);
            holder.tv_name.setText(name);
            holder.count.setText(mPlayerCount.get(name));
            holder.tv_date.setText(mSignDate.get(name)==null?"无记录":mSignDate.get(name));
            if(TimeUtil.getDate().equals(mSignDate.get(name))){
                holder.bt_sign.setVisibility(View.GONE);
                holder.bt_signed.setVisibility(View.VISIBLE);
            }else{
                holder.bt_sign.setVisibility(View.VISIBLE);
                holder.bt_signed.setVisibility(View.GONE);
            }


            return convertView;
        }
    }

    static class ViewHolder{
        TextView tv_name;
        TextView count;
        TextView tv_date;
        Button bt_sign;
        Button bt_signed;
        Button bt_delplayer;
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                Object mHelperUtils;
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                Log.e(this.getLocalClassName(), "再按一次退出程序");
                mExitTime = System.currentTimeMillis();

            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}